var fs = require('fs');
var connect = require('connect');
var mysql = require('mysql');
var socketio = require('socket.io');

// connect to database
var client = mysql.createConnection({
	user: 'root',
	password: 'welcome1',
	database: 'location'
});

// create web server
var server = connect.createServer();
server.use(connect.query());
server.use(connect.router(function(app) {
	// GET - /tracker
	app.get('/tracker', function(request, response) {
		fs.readFile('./resources/tracker.html', function(error, data) {
			response.writeHead(200, {'Content-Type': 'text/html'});
			response.end(data);
		});
	});
	
	// GET - /observer
	app.get('/observer', function(request, response) {
		fs.readFile('./resources/observer.html', function(error, data) {
			response.writeHead(200, {'Content-Type': 'text/html'});
			response.end(data);
		});
	});
	
	// GET - /show
	app.get('/show', function(request, response) {
		client.query('SELECT * FROM locations WHERE name = ?', [request.query.name], function(error, data) {
			response.writeHead(200, {'Content-Type': 'application/json'});
			response.end(JSON.stringify(data));
		});
	});
}));

// run web server
server.listen(52273, function() {
	console.log('Server running at http://localhost:52273');
});

// create and run socket server
var io = socketio.listen(server);
io.sockets.on('connection', function(socket) {
	// join event
	socket.on('join', function(data) {
		console.log('join:' +  data);
		socket.join(data);
	});
	
	// location event
	socket.on('location', function(data) {
		// insert data
		client.query('INSERT INTO locations (name, latitude, longitude, date) VALUES (?, ?, ?, NOW())', 
				[data.name, data.latitude, data.longitude]);
		
		// emit receive event
		io.sockets['in'](data.name).emit('receive', {
			latitude: data.latitude,
			longitude: data.longitude,
			date: new Date().toUTCString()
		});
	});
});